package com.zmn.oms.dubbo.impl.zmn.master.additionalorder;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.erp.common.dro.MasterAddMoreOrderBonusDRO;
import com.zmn.erp.common.dro.MasterAddMoreOrderBonusOneMonthDRO;
import com.zmn.erp.dubbo.interfaces.newbiz.account.EngineerAccountRemoteService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.enums.EncryptFieldTypeEnum;
import com.zmn.oms.dubbo.dto.zmn.order.masteradditionalorder.MasterAdditionalOrderListDRO;
import com.zmn.oms.dubbo.dto.zmn.order.masteradditionalorder.MasterAdditionalOrderPageDRO;
import com.zmn.oms.dubbo.dto.zmn.order.masteradditionalorder.OrderAddressDRO;
import com.zmn.oms.dubbo.impl.zmn.order.OrderWorkBaseRemoteService;
import com.zmn.oms.dubbo.interfaces.zmn.master.additionalorder.MasterAdditionalOrderRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.oms.services.interfaces.orderencrypt.OrderEncryptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：工程师加单
 *
 * @author yule
 * @date 2020/5/12 11:19
 */
@Slf4j
@Service(loadbalance = "roundrobin", timeout = 5000, retries = 2, version = DubboConsts.INTERFACE_VERSION, validation = "false")
public class MasterAdditionalOrderRemoteServiceImpl extends OrderWorkBaseRemoteService implements MasterAdditionalOrderRemoteService {

    @Autowired
    OrderWorkListBService orderWorkListBService;
    @Autowired
    OrderEncryptService orderEncryptService;

    @Reference(version = com.zmn.erp.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
    EngineerAccountRemoteService engineerAccountRemoteService;

    @Override
    public ResponseDTO<MasterAdditionalOrderPageDRO> getAdditionalOrderListByMasterId(Integer masterId, Date month) {
        try {
            if (month == null) {
                // 如果没提供月份，默认查当月
                month = DateUtil.getNow();
            }

            String monthFirstDay = DateUtil.getMonthFirstDay(month);
            String monthLastDay = DateUtil.getMonthLastDay(month);

            OrderWorkQuery query = new OrderWorkQuery();
            query.setRecommenderId((long) masterId);
            query.setRecommenderType((long) GlobalConsts.OPERATE_USER_TYPE_MASTER);
            query.setReceiveTime(monthFirstDay + "," + monthLastDay);
            query.setDefaultOrder(GlobalConsts.YES);
            query.setOrderField("receiveTime");
            // 查询
            List<EsOrderWork> esOrderWorks = orderWorkListBService.listPageOrderWorkByQuery(query);
            MasterAdditionalOrderPageDRO additionalOrder = new MasterAdditionalOrderPageDRO();
            additionalOrder.setTotalCount(query.getTotalCount());

            if (CollectionUtils.isEmpty(esOrderWorks)) {
                ResponseDTO.success(additionalOrder);
            }

            // erp接口获取指定月份指定工程师加单奖励金
            ResponseDTO<MasterAddMoreOrderBonusOneMonthDRO> responseDTO = engineerAccountRemoteService.getAddMoreOrderBonus4DesignatedMonth(month, masterId);
            logger.info("erp接口获取指定月份指定工程师加单奖励金出参---【{}】", JSON.toJSON(responseDTO));
            // erp接口获取指定月份指定工程师加单奖励金 --- 指定月加单奖励接口删除
            //TODO
            Map<Long, Integer> bonusDetail = new HashMap();
            if (responseDTO.isSuccess() && Objects.nonNull(responseDTO.getData())) {
                // 指定月份加单佣金
                additionalOrder.setSpecifyMonthCommission(Optional.ofNullable(responseDTO.getData().getTotalInOneMonth()).orElse(0));
                bonusDetail = responseDTO.getData().getBonusDetails();
            }

            Map<Long, Integer> finalBonusDetail = bonusDetail;
            List<MasterAdditionalOrderListDRO> orderList = Lists.newArrayListWithCapacity(esOrderWorks.size());
            esOrderWorks.forEach(esOrderWork -> {
                MasterAdditionalOrderListDRO orderListDRO = BeanMapper.map(esOrderWork, MasterAdditionalOrderListDRO.class);
                orderListDRO.setWorkId(esOrderWork.getId());

                if (Objects.nonNull(finalBonusDetail)) {
                    orderListDRO.setAdditionalCommission(finalBonusDetail.get(esOrderWork.getOrderId()));
                }

                orderList.add(orderListDRO);
            });

            additionalOrder.setList(orderList);

            // erp接口获取工程师本月，上月，以及累计加单奖励金额
            ResponseDTO<MasterAddMoreOrderBonusDRO> resp = engineerAccountRemoteService.getAddMoreOrderBonus(masterId);
            logger.info("erp接口获取工程师本月，上月，以及累计加单奖励金额出参【{}", resp);
            if (resp.isSuccess() && Objects.nonNull(resp.getData())) {
                MasterAddMoreOrderBonusDRO orderBonus = resp.getData();
                additionalOrder.setAdditionalCurrentMonthCommission(Optional.ofNullable(orderBonus.getCurrentMonthAmount()).orElse(0));
                additionalOrder.setAdditionalLastMonthCommission(Optional.ofNullable(orderBonus.getLastMonthAmount()).orElse(0));
                additionalOrder.setAdditionalTotalCommission(Optional.ofNullable(orderBonus.getTotalAmount()).orElse(0));
            }
            //TODO 接口删除

            return ResponseDTO.success(additionalOrder);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseDTO.fail(e.getMessage());
        }
    }

    @Override
    public ResponseDTO<List<OrderAddressDRO>> getThreeDaysOrderAddressByMasterId(Integer masterId) {
        OrderWorkQuery query = new OrderWorkQuery();

        //按预约时间，取最近3天（含当天）该工程师服务的订单对应的用户地址
        Date startTime = DateUtil.addDays(new Date(), -2);
        String startTimeStr = DateUtil.toString(startTime, "yyyy-MM-dd 00:00:00");
        String endTimeStr = DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd 23:59:59");

        query.setDutyTime(startTimeStr + "," + endTimeStr);
        query.setDefaultOrder(GlobalConsts.YES);
        query.setOrderField("receiveTime");
        query.setMasterId(masterId);
        List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);
        if (esOrderWorkList.isEmpty()) {
            return ResponseDTO.success();
        }
        // 解密电话和地址
        orderEncryptService.batchDecryptEsOrderWork(esOrderWorkList, EncryptFieldTypeEnum.USER_TELPHONE, EncryptFieldTypeEnum.USER_ADDRESS);

        List<OrderAddressDRO> orderContactList = Lists.newArrayListWithCapacity(esOrderWorkList.size());
        esOrderWorkList.forEach((item) -> {
            OrderAddressDRO orderContact = new OrderAddressDRO();
            orderContact.setUserName(item.getContact().getUserName());
            orderContact.setUserPhone(item.getContact().getPhone()[0]);
            orderContact.setProvinceName(item.getProvinceName());
            orderContact.setCityName(item.getCityName());
            orderContact.setCountyName(item.getCountyName());
            orderContact.setStreet(item.getContact().getStreet());
            orderContact.setAddress(item.getContact().getAddress());

            if (StringUtils.isNotBlank(item.getContact().getLocation())) {
                String[] arr = item.getContact().getLocation().split(",");
                orderContact.setLatitude(Double.valueOf(arr[0]));
                orderContact.setLongitude(Double.valueOf(arr[1]));
            }

            orderContact.setCityId(item.getCityId());
            orderContactList.add(orderContact);

        });

        if (CollectionUtils.isEmpty(orderContactList)) {
            return ResponseDTO.success();
        }

        // 过滤姓名为空的数据
        List<OrderAddressDRO> filterList = orderContactList.stream().filter(item -> StringUtils.isNotBlank(item.getUserName())).collect(Collectors.toList());

        // 根据 经纬度、详细地址、用户电话、用户姓名筛选去重复
        List<OrderAddressDRO> distinctOrderContactList = filterList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(
                o -> o.getUserName() + ";" + o.getUserPhone() + ";"
                        + o.getLongitude() + ";" + o.getLatitude() + ";"
                        + o.getAddress() + ";" + o.getStreet()))), ArrayList::new));


        return ResponseDTO.success(distinctOrderContactList);
    }


}

